package com.example.sunmi.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmi.Base.BaseActivity;
import com.example.sunmi.Bean.BaseBean;
import com.example.sunmi.R;
import com.example.sunmi.Utils.AidlUtil;
import com.example.sunmi.Utils.Customer;
import com.example.sunmi.Utils.DensityUtil;
import com.example.sunmi.Utils.DesUtils;
import com.example.sunmi.Utils.ErrorFileUtils;
import com.example.sunmi.Utils.FaceCj;
import com.example.sunmi.Utils.LogUtil;
import com.example.sunmi.Utils.MyBitmapUtils;
import com.example.sunmi.Utils.PermissionsUtils;
import com.example.sunmi.Utils.SPUtils;
import com.example.sunmi.Utils.ScreenUtil;
import com.example.sunmi.Utils.TimeUtil;
import com.example.sunmi.Utils.ToastUtil;
import com.example.sunmi.Utils.httpUtils;
import com.example.sunmi.widget.EditView;
import com.example.sunmi.widget.SKeyboardView;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import woyou.aidlservice.jiuiv5.IWoyouService;


public class MainActivity extends BaseActivity implements View.OnClickListener {

    private Button IDCard;
    private Button Gatxz;
    private Button Pass;
    private ImageView ivHead;
    private TextView tvName;
    private EditText etName;
    private TextView tvNumber;
    private EditView etNumber;
    private Button BtPhoto;
    private Button BtPrint;
    private ImageView Setting;
    private boolean hasPermissions;
    private final int REQUEST_CODE = 1;
    private Uri mUri;
    private final int REQUEST_TAKE_PHOTO_CODE = 101;
    private static final int Toasts = 0;
    private static final int GO_TO_PRINT = 1;
    private MyHandler mMyHandler = new MyHandler(this);
    //打印格式
    private static String printTitle = "   游客临时身份证明";
    //    private String printTitle_en = "   游客临时身份证明";
    private Bitmap bitmapHead;
    private static int print_size = 6;
    private static int error_level = 3;

    private static String number;
    private static String name;
    private int Seltype = 1;
    private LinearLayout llKeyboard;
    private SKeyboardView keyboardView;
    private int height = 0;
    LinearLayout llGuan;

    private String BaseUrl;
    private static String qr;

    String[] permissions = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET,
    };

    private static class MyHandler extends Handler {
        private WeakReference<MainActivity> activityWeakReference;

        public MyHandler(MainActivity activity) {
            activityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            final MainActivity activity = activityWeakReference.get();
            switch (msg.what) {
                case Toasts:
                    break;
                case GO_TO_PRINT:
//                    GotoPrint();
                    break;
            }

        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //生请权限
        permissRequset();
    }

    private void permissRequset() {
        PermissionsUtils.getInstance().chekPermissions(this, permissions, permissionsResult);
    }

    @Override
    public int initId() {
        return R.layout.activity_main;
    }


    @Override
    public void initView() {
        IDCard = (Button) findViewById(R.id.bt_idCard);
        Gatxz = (Button) findViewById(R.id.bt_gatxz);
        Pass = (Button) findViewById(R.id.bt_pass);
        ivHead = (ImageView) findViewById(R.id.iv_image);
        ivHead.setPadding(20, 20, 20, 20);
        tvName = (TextView) findViewById(R.id.tv_name);
        etName = (EditText) findViewById(R.id.et_name);

        tvNumber = (TextView) findViewById(R.id.tv_number);
        etNumber = (EditView) findViewById(R.id.et_number);

        BtPhoto = (Button) findViewById(R.id.bt_photo);
        BtPrint = (Button) findViewById(R.id.bt_print);

        Setting = (ImageView) findViewById(R.id.iv_setting);

        llKeyboard = (LinearLayout) findViewById(R.id.ll_keyboard);
        keyboardView = (SKeyboardView) findViewById(R.id.keyboard_view);
        llGuan = (LinearLayout) findViewById(R.id.ll_input);

        IDCard.setOnClickListener(this);
        Gatxz.setOnClickListener(this);
        Pass.setOnClickListener(this);
        BtPhoto.setOnClickListener(this);
        BtPrint.setOnClickListener(this);
        Setting.setOnClickListener(this);

        //获取配置文件
        BaseUrl = (String) SPUtils.get(MainActivity.this, Customer.CONFIG_URL, Customer.BASE_URL);
        setSubView();
        initEvent();
    }

    private void initEvent() {

        etNumber.setOnKeyboardListener(new EditView.OnKeyboardListener() {
            @Override
            public void onHide(boolean isCompleted) {
                if (height > 0) {
                    llGuan.scrollBy(0, -(height + DensityUtil.dp2px(MainActivity.this, 16)));
                }

                if (isCompleted) {
                    LogUtil.i("", "你点击了完成按钮");
                }
            }

            @Override
            public void onShow() {
                llGuan.post(new Runnable() {
                    @Override
                    public void run() {
                        //pos[0]: X，pos[1]: Y
                        int[] pos = new int[2];
                        //获取编辑框在整个屏幕中的坐标
                        etNumber.getLocationOnScreen(pos);
                        //编辑框的Bottom坐标和键盘Top坐标的差
                        height = (pos[1] + etNumber.getHeight())
                                - (ScreenUtil.getScreenHeight(MainActivity.this) - keyboardView.getHeight());
                        if (height > 0) {
                            //编辑框和键盘之间预留出16dp的距离
                            llGuan.scrollBy(0, height + DensityUtil.dp2px(MainActivity.this, 16));
                        }
                    }
                });
            }

            @Override
            public void onPress(int primaryCode) {

            }
        });
    }

    private void setSubView() {
        etNumber.setEditView(llKeyboard, keyboardView, true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_idCard:
                Seltype = 1;
                changeFace(1);
                break;
            case R.id.bt_gatxz:
                Seltype = 2;
                changeFace(2);
                break;
            case R.id.bt_pass:
                Seltype = 3;
                changeFace(3);
                break;
            case R.id.bt_photo:
                if (hasPermissions) {
                    takePhoto();//拍照逻辑
                } else {
                    ToastUtil.showToast("拍照权限未打开，请手动打开拍照权限");
                }
                break;
            case R.id.bt_print:
                name = etName.getText().toString().trim();
                number = etNumber.getText().toString().trim();

                if (number.equals("") || name.equals("")) {
                    ToastUtil.showToast("个人信息填写不完整");
                    return;
                }

                if (Seltype == 1 && !isLegalId(number)) {
                    ToastUtil.showToast("身份证格式错误，请重新确认");
                    return;
                }

                if (Seltype == 2 && !isLegalGA(number)) {
                    ToastUtil.showToast("港澳通行证格式错误，请重新确认");
                    return;
                }
                if (Seltype == 2 && !isLegalT(number)) {
                    ToastUtil.showToast("台湾通行证格式错误，请重新确认");
                    return;
                }
                if (Seltype == 3 && !isLegalgaPass(number)) {
                    ToastUtil.showToast("护照通行证格式错误，请重新确认");
                    return;
                }
                //去打印
//                try {
//                    qr = DesUtils.encrypt(this.number);
//                    sendDataToSeverTest(DesUtils.encrypt(name), qr);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                if (bitmapHead != null) {
                    try {
                        qr = DesUtils.encrypt(this.number);
                        //通过接口，发送数据到服务器
                        Bitmap bitmap = MyBitmapUtils.scaleImageTo(bitmapHead, 260, 320);
                        sendDataToSever(DesUtils.encrypt(name), qr, bitmap);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast("请先拍摄人脸照片。");
                    return;
                }
                break;
            case R.id.iv_setting:
                inputTitleDialog();
                break;
        }

    }

    private void GotoPrint() {
        ToastUtil.showToast("我去打印了");
        LogUtil.v("咋们去打印了");
        AidlUtil.getInstance().printText("★★★★★★★★★★★★★★", 26, false, false);
        AidlUtil.getInstance().printText(printTitle, 30, true, false);
        AidlUtil.getInstance().printText("★★★★★★★★★★★★★★", 26, false, false);

        AidlUtil.getInstance().printQr(qr, print_size, error_level);

        AidlUtil.getInstance().printText("姓名: " + name, 26, false, false);
        AidlUtil.getInstance().printText("证件号: " + number, 26, false, false);

        AidlUtil.getInstance().printText("★★★★★★★★★★★★★★", 26, false, false);
        AidlUtil.getInstance().printText("打印时间: " + TimeUtil.getLocationTime(), 26, false, false);
        AidlUtil.getInstance().printTextLineMax("★★★★★★★★★★★★★★", 26, false, false);

        //打印完成 然后才去清空
        etName.setText("");
        etNumber.setText("");
        ivHead.setPadding(20, 20, 20, 20);
        ivHead.setScaleType(ImageView.ScaleType.FIT_CENTER);
        ivHead.setImageResource(R.mipmap.person);
        bitmapHead = null;
    }

    private void inputTitleDialog() {
        final EditText inputServer = new EditText(this);
        inputServer.setHint(BaseUrl);
        inputServer.setText(BaseUrl);
        inputServer.setFocusable(true);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.Dlalog_title))
                .setView(inputServer).setNegativeButton(
                getString(R.string.Dlalog_cancle), null);
        builder.setPositiveButton(getString(R.string.Dlalog_confirm),
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        String inputName = inputServer.getText().toString().trim();
//                        String baseUrl = (String) SPUtils.get(MainActivity.this, Customer.CONFIG_URL, Customer.BASE_URL);
                        if (inputName != null) {
                            SPUtils.put(MainActivity.this, Customer.CONFIG_URL, inputName);
                            BaseUrl = inputName;
                        }
                    }
                });
        builder.show();

    }

    private void sendDataToSever(final String name, final String number, final Bitmap bitmap) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String base64 = MyBitmapUtils.bitmapToBase64(bitmap);
                // 先封装一个 JSON 对象
                Map<String, String> params = new HashMap<String, String>();
                params.put("certificateName", name);
                params.put("certificateNo", number);
                params.put("photoBase64", base64);
                final String url = "http://" + BaseUrl + Customer.UP_BASE64_URL;
                final String ss = httpUtils.postMap(url, params);
                try {
                    BaseBean baseBean = new Gson().fromJson(ss, BaseBean.class);
                    if (baseBean.getCode().equals("0")) {
                        //服务器 访问 成功后 再去打印
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                GotoPrint();
                            }
                        });
                        ToastUtil.showToast(baseBean.getMessage());
                    } else {
                        ToastUtil.showToast(baseBean.getMessage() + "打印机没法打印");
                    }

                } catch (Exception e) {
                    ErrorFileUtils.getInstance().saveStringToFile("传入地址：" + url + "     传入参数：" + params.toString() + "    访问返回参数" + ss);
                    ErrorFileUtils.getInstance().cleanErrorText();
                    ToastUtil.showToast("保存失败:  传入地址：" + url + "    访问返回失败参数" + ss);

                }
            }
        }).start();

    }

//    private void sendDataToSeverTest(final String name, final String number) {
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
////                String base64 = MyBitmapUtils.bitmapToBase64(bitmap);
//                // 先封装一个 JSON 对象
//                Map<String, String> params = new HashMap<String, String>();
//                params.put("certificateName", name);
//                params.put("certificateNo", number);
//                final String url = "http://" + BaseUrl + Customer.UP_BASE64_URL;
//                final String ss = httpUtils.postMap(url, params);
//                try {
//                    BaseBean baseBean = new Gson().fromJson(ss, BaseBean.class);
//                    ToastUtil.showToast(baseBean.getMessage());
//                    //服务器 访问 成功后 再去打印
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            GotoPrint();
//                        }
//                    });
//                } catch (Exception e) {
//
//                    //服务器 访问 成功后 再去打印
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            GotoPrint();
//                        }
//                    });
//
//                    ErrorFileUtils.getInstance().saveStringToFile("传入地址：" + url + "     传入参数：" + params.toString() + "    访问返回参数" + ss);
//                    ErrorFileUtils.getInstance().cleanErrorText();
//                    ToastUtil.showToast("保存失败:  传入地址：" + url + "    访问返回失败参数" + ss);
//
//                }
//            }
//        }).start();
//
//    }

    private void changeFace(int type) {
        switch (type) {
            case 1:
                IDCard.setBackgroundResource(R.drawable.shape_bule);
                IDCard.setTextColor(Color.WHITE);
                Gatxz.setBackgroundResource(R.drawable.shape_white);
                Gatxz.setTextColor(Color.BLACK);
                Pass.setBackgroundResource(R.drawable.shape_white);
                Pass.setTextColor(Color.BLACK);

                tvName.setText("姓名 :");
                tvNumber.setText("证件号 :");

                etName.setHint("请输入姓名");
                etNumber.setHint("请输入证件号");
//
//                BtPhoto.setText("拍照");
//                BtPrint.setText("打印");

                break;
            case 2:

                IDCard.setBackgroundResource(R.drawable.shape_white);
                IDCard.setTextColor(Color.BLACK);
                Gatxz.setBackgroundResource(R.drawable.shape_bule);
                Gatxz.setTextColor(Color.WHITE);
                Pass.setBackgroundResource(R.drawable.shape_white);
                Pass.setTextColor(Color.BLACK);

                tvName.setText("姓名 :");
                tvNumber.setText("證件號 :");

                etName.setHint("請輸入姓名");
                etNumber.setHint("請輸入證件號");
//
//                BtPhoto.setText("拍照");
//                BtPrint.setText("打印");

                break;
            case 3:

                IDCard.setBackgroundResource(R.drawable.shape_white);
                IDCard.setTextColor(Color.BLACK);
                Gatxz.setBackgroundResource(R.drawable.shape_white);
                Gatxz.setTextColor(Color.BLACK);
                Pass.setBackgroundResource(R.drawable.shape_bule);
                Pass.setTextColor(Color.WHITE);

                tvName.setText("Name :");
                tvNumber.setText("ID Number :");

                etName.setHint("Please enter your name");
                etNumber.setHint("Please enter your id number");
//
//                BtPhoto.setText("Photo");
//                BtPrint.setText("Print");

                break;
        }
    }


    private void takePhoto() {
        // 步骤一：创建存储照片的文件
        String path = getFilesDir() + File.separator + "images" + File.separator;
        File file = new File(path, "test.jpg");
        if (!file.getParentFile().exists())
            file.getParentFile().mkdirs();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //步骤二：Android 7.0及以上获取文件 Uri
            mUri = FileProvider.getUriForFile(MainActivity.this, "com.example.sunmi", file);
        } else {
            //步骤三：获取文件Uri
            mUri = Uri.fromFile(file);
        }
        //步骤四：调取系统拍照
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        startActivityForResult(intent, REQUEST_TAKE_PHOTO_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_TAKE_PHOTO_CODE) {
            Bitmap bm = null;
            try {
                bm = getBitmapFormUri(mUri);
                bitmapHead = bm;
//                MyBitmapUtils.saveBitmap2(bitmapHead);
//                LogUtil.v("bitmap原始图大小---" + FaceCj.getPrintSize(FaceCj.getBitmapSize(bm)));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            ivHead.setPadding(0, 0, 0, 0);
            ivHead.setScaleType(ImageView.ScaleType.CENTER_CROP);
            ivHead.setImageBitmap(bm);

        }
    }

    public Bitmap getBitmapFormUri(Uri uri) throws FileNotFoundException, IOException {
        InputStream input = getContentResolver().openInputStream(uri);

        //这一段代码是不加载文件到内存中也得到bitmap的真是宽高，主要是设置inJustDecodeBounds为true
        BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
        onlyBoundsOptions.inJustDecodeBounds = true;//不加载到内存
        onlyBoundsOptions.inDither = true;//optional
        onlyBoundsOptions.inPreferredConfig = Bitmap.Config.RGB_565;//optional
        BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
        input.close();
        int originalWidth = onlyBoundsOptions.outWidth;
        int originalHeight = onlyBoundsOptions.outHeight;
        if ((originalWidth == -1) || (originalHeight == -1))
            return null;

        //图片分辨率以480x800为标准
//        float hh = 800f;//这里设置高度为800f
//        float ww = 480f;//这里设置宽度为480f
        float hh = 320f;//这里设置高度为320f
        float ww = 260f;//这里设置宽度为260f

        //缩放比，由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (originalWidth > originalHeight && originalWidth > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (originalWidth / ww);
        } else if (originalWidth < originalHeight && originalHeight > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (originalHeight / hh);
        }
        if (be <= 0)
            be = 1;
        //比例压缩
        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inSampleSize = be;//设置缩放比例
        bitmapOptions.inDither = true;
        bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
        input = getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
        input.close();

        return compressImage(bitmap);//再进行质量压缩
    }

    public Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
            if (options <= 0)
                break;
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    //创建监听权限的接口对象
    PermissionsUtils.IPermissionsResult permissionsResult = new PermissionsUtils.IPermissionsResult() {
        @Override
        public void passPermissons() {
            //有权限去干啥
            hasPermissions = true;
        }

        @Override
        public void forbitPermissons() {
            // 没有权限干啥
            hasPermissions = false;
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionsUtils.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * 验证输入的身份证号是否合法
     */
    public static boolean isLegalId(String id) {
        if (id.toUpperCase().matches("(^\\d{15}$)|(^\\d{17}([0-9]|X)$)")) {
            return true;
        } else {
            return false;
        }
    }

    //验证港澳通行证 合法
    public static boolean isLegalGA(String id) {
        if (id.toUpperCase().matches("/^([A-Z]\\d{6,10}(\\w1)?)$/")) {
            return true;
        } else {
            return false;
        }
    }

    //验证台湾合法
    public static boolean isLegalT(String id) {
        if (id.toUpperCase().matches("/^[a-zA-Z][0-9]{9}$/")) {
            return true;
        } else {
            return false;
        }
    }

    //验证护照合法
    public static boolean isLegalgaPass(String id) {
        if (id.toUpperCase().matches("/^1[45][0-9]{7}$|([P|p|S|s]\\d{7}$)|([S|s|G|g]\\d{8}$)|([Gg|Tt|Ss|Ll|Qq|Dd|Aa|Ff]\\d{8}$)|([H|h|M|m]\\d{8,10})$/")) {
            return true;
        } else {
            return false;
        }
    }
}
